#!/usr/bin/env bash

set -e

### cfgs here
readonly TARGET=bazel
readonly VERSION=5.0.0
readonly URL=https://github.com/bazelbuild/bazel/releases/download/${VERSION}/bazel-${VERSION}-dist.zip
readonly OUTDIR="/opt/bazel"

function build_bazel {
    # build cmd
    local pkg=${TARGET}-${VERSION}.zip
    local work_dir=${TARGET}-${VERSION}

    apt-get update && apt-get install -fy openjdk-11-jdk-headless

    [ -d ${OUTDIR} ] || mkdir -p ${OUTDIR}
    pushd ${OUTDIR} > /dev/null
        wget -c ${URL} -O $pkg
        [ -x "$(command -v unzip)" ] || $(apt-get update && apt-get -y install unzip)
        [ -d ${work_dir} ] && rm -rf ${work_dir}
        unzip $pkg -d ${work_dir}
        pushd ${work_dir} > /dev/null
            bash ./compile.sh && cp ./output/bazel /usr/local/bin/
        popd > /dev/null
    popd > /dev/null
}

function main {
    build_bazel
    [ -x "$(command -v bazel)" ] && rm -rf ${OUTDIR}
}

main "$@"
